package com.ckm.datasource;

import com.ckm.context.DynamicMongoContextHolder;
import com.ckm.provider.DynamicMongoSourceProvider;
import com.mongodb.ClientSessionOptions;
import com.mongodb.client.ClientSession;
import com.mongodb.client.MongoDatabase;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.data.mongodb.MongoDatabaseFactory;

import java.util.List;

public class DynamicMongoFactory extends AbstractRoutingMongoSource implements MongoDatabaseFactory {
    public DynamicMongoFactory(List<DynamicMongoSourceProvider> providers) {
        super(providers);
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicMongoContextHolder.getMongoContext();
    }

    public MongoDatabaseFactory getMongoDatabaseFactory(){
        return determineMongoDatabaseFactory();
    }

    @Override
    public MongoDatabase getMongoDatabase() throws DataAccessException {
        return getMongoDatabaseFactory().getMongoDatabase();
    }

    @Override
    public MongoDatabase getMongoDatabase(String dbName) throws DataAccessException {
        return getMongoDatabaseFactory().getMongoDatabase(dbName);
    }

    @Override
    public PersistenceExceptionTranslator getExceptionTranslator() {
        return getMongoDatabaseFactory().getExceptionTranslator();
    }

    @Override
    public ClientSession getSession(ClientSessionOptions options) {
        return getMongoDatabaseFactory().getSession(options);
    }

    @Override
    public MongoDatabaseFactory withSession(ClientSession session) {
        return getMongoDatabaseFactory().withSession(session);
    }
}
